package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import com.itheima.pojo.Role;
import com.itheima.pojo.UserEditVo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    @RequestMapping("/getUserName")
    public Result getUserName() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return Result.success("", user.getUsername());
    }


    @RequestMapping("/getMeunList")
    public Result getMeunList(){

        String username = (String) getUserName().getData();
        List<Menu> menuList = userService.getMeunList(username);

        return Result.success("",menuList);
    }

    @RequestMapping("/findAllRoles")
    public Result findAllRoles() {
        List<Role> roles = userService.findAll();
        return new Result(true, "", roles);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user) {
        try {
            userService.add(user);
            return new Result(true, "添加用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加用户失败");
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

        PageResult pageResult = (PageResult) userService.findPage(queryPageBean);
        return pageResult;
    }
    @RequestMapping("/find4Edit")
    public Result find4Edit(Integer id) {
        try {
            UserEditVo userEditVo = userService.find4Edit(id);
            return new Result(true, "", userEditVo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "");
        }
    }
    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user) {
        try {
            userService.edit(user);
            return new Result(true, "修改用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改用户失败");
        }
    }
    @RequestMapping("/delete")
    public Result edit(Integer id) {
        try {
            userService.delete(id);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改失败");
        }
    }
}
